<?php


namespace App\Kuafu\Sms\Controller\Merchant;


use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Sms\Service\SmsService;
use App\Kuafu\Sys\Exceptions\SysException;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Model\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SmsController extends BaseController
{

    /**
     * 发送短信验证码
     * @param $mobile
     * @param $type
     * @return JsonResponse
     * @throws \Exception
     */
    public function sendSms(Request $request)
    {
        $mobile = $request->mobile;
        $type   = $request->type ?: 0;

        SmsService::sendSms($mobile, $type);

        return $this->success(['msg' => 'ok']);
    }

    /**
     * 验证短信验证码
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Kuafu\Sms\Exceptions\SmsException
     */
    public function verifyCode(Request $request)
    {
        SmsService::verifyCode($request->mobile, $request->code, $request->type);
        return $this->success();
    }

    /**
     * 检查手机号登录
     * @throws UserException
     */
    public function checkMobileLogin(Request $request): JsonResponse
    {
        $mobile = $request->mobile;
        if (!preg_match("/^1[3456789]\d{9}$/", $mobile)) {
            throw new UserException(UserCodeEnum::ERR_USER_MOBILE);
        }
        $user = User::query()->where("mobile", $mobile)->first();

        // 用户不存在 返回异常
        if (empty($user)) {
            return $this->fail(UserCodeEnum::ERR_USER_MERCHANT_APP_LOGIN_NOT_EXIST,
                UserCodeEnum::CODE_TEXT[UserCodeEnum::ERR_USER_MERCHANT_APP_LOGIN_NOT_EXIST]);
        }

        return $this->success();
    }

}
